import socket

def get_local_ip():
    try:
        # 创建一个UDP套接字
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # 连接到一个外部地址
        s.connect(("8.8.8.8", 80))
        # 获取本地IP地址
        local_ip = s.getsockname()[0]
        s.close()
        return local_ip
    except Exception as e:
        print(f"获取IP失败: {e}")
        # 作为备选，获取环回地址
        return socket.gethostbyname(socket.gethostname())

print("本机IP地址:", get_local_ip())